package com.example.lanouhn.firstapp.activity.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.adapter.BrokerDealerAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.model.BrokerDealer;
import com.example.lanouhn.firstapp.activity.model.OneSyomb;
import com.example.lanouhn.firstapp.activity.model.Syomb;
import com.example.lanouhn.firstapp.activity.utils.BrokerdealerJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.utils.OneSyombJson;
import com.example.lanouhn.firstapp.activity.utils.OneToastUtils;
import com.example.lanouhn.firstapp.activity.utils.SPUtils;
import com.example.lanouhn.firstapp.activity.utils.SyombJson;
import com.example.lanouhn.firstapp.activity.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

//自营按钮跳转的商城页面
public class BrokerDealerActivity extends AppCompatActivity implements View.OnClickListener,
        PlatformActionListener {

    private ShareDialog shareDialog;
    //推荐商品
    private RecyclerView recyclerView;
    //新品推荐
    private RecyclerView newRecyclerView;
    //数据集合
    private List<BrokerDealer> list;
    //适配器
    private BrokerDealerAdapter adapter;
    //定义进度加载 ProgressBar
    private ProgressBar progressBar;

    //电话
    private RelativeLayout phone;
    //分享
    private RelativeLayout share;
    //商店描述
    private ImageView iv_store_credit;

    //全部商品
    private LinearLayout all_goods;
    //返回
    private ImageView iv_back;
     //搜索
    private ImageView iv_search;
    private EditText et_search;

    //商城关注按钮
    private RelativeLayout rl_attention;
    private TextView tv_attention;
    private RadioButton iv_attention;
    //QQ
    private RelativeLayout qq;


    private String key;
    private int store_id = 1;
    //判断标识
    private Syomb SList;
    private OneSyomb OSList;

    //线程
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //取消进度
            progressBar.setVisibility(View.GONE);
            super.handleMessage(msg);
            switch (msg.what) {

                case 0:
                    showDialogAgain(BrokerDealerActivity.this, "网络链接失败....", false);
                    break;
                case 1:
                    //创建adapter
                    adapter = new BrokerDealerAdapter(list, BrokerDealerActivity.this);
                    //绑定adapter
                    recyclerView.setAdapter(adapter);
                    newRecyclerView.setAdapter(adapter);
                    //执行完毕，更新UI,
                    adapter.notifyDataSetChanged();
                    //点击跳转到商品详情
                    adapter.setBrokerDealerRecyclerViewListener
                            (new BrokerDealerAdapter.
                                    BrokerDealerRecyclerViewListener() {
                        @Override
                        public void onClick(View view, int position) {
                            Intent intent = new Intent
                                    (BrokerDealerActivity.this,GoodsDetailsActivity.class);
                            //携带商品id进行跳转
                            intent.putExtra("goods_id",list.get(position).getGoods_id());
                            startActivity(intent);

                        }
                    });

                    break;
                case 2:

                    OneToastUtils.showToast(
                            getApplicationContext(), R.mipmap.xiao_lan, "收藏成功");
                    break;
                case 3:
                    ToastUtils.showToast(
                            getApplicationContext(), R.mipmap.xiao_lan, "您已收藏该店铺了");
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_brokedealer);
        //获取key
        key = (String) SPUtils.get(BrokerDealerActivity.this,"log_key","");

        //绑定控件
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        newRecyclerView = (RecyclerView) findViewById(R.id.newRecyclerView);
        //设置图片距离
        BrokerDealerActivity.SpacesItemDecoration decoration = new SpacesItemDecoration(9);
        //推荐商品图片的距离
        recyclerView.addItemDecoration(decoration);
        newRecyclerView.addItemDecoration(decoration);

        //加载推荐商品列表布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        //加载新品推荐列表布局管理器
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 2);
        newRecyclerView.setLayoutManager(gridLayoutManager1);
        //找到控件
        initView();
        //监听事件
        initEvent();
        ShareSDK.initSDK(this);
        //请求网络数据
        getDataFromWeb();

    }

    private void initEvent() {
        //QQ
        qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialogQQ();
            }
        });


        //商店描述 弹出对话框
        iv_store_credit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialogStore();
            }
        });

        tv_attention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //点击关注后变换图片
                iv_attention.setChecked(true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if(!recyclerView.equals("")){

                            String url = "http://www.niaolema.com/mobile/index.php?act=member_favorites_store&op=favorites_add";
                            String params ="key=" + key + "&store_id=" + store_id;
                            String result = HttpUtils.doPost(url, params);
                            OSList = OneSyombJson.getOneSyomb(result);
                            //if(OSList.getError().equals("")){
                            handler.sendEmptyMessage(3);
                            //}

                        } else {

                            String url = "http://www.niaolema.com/mobile/index.php?act=member_favorites_store&op=favorites_add";
                            String params ="key=" + key + "&store_id=" + store_id;
                            String result = HttpUtils.doPost(url, params);
                            if (!result.equals("") && !result.equals("null")) {
                                SList = SyombJson.getSyomb(result);
                                if (SList.getDatas() == 1) {
                                    //获取数据成功
                                    handler.sendEmptyMessage(2);
                                } else {
                                    handler.sendEmptyMessage(0);
                                }

                            }
                        }


                    }
                }).start();


            }
        });

        rl_attention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //点击关注后变换图片
                iv_attention.setChecked(true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if(!recyclerView.equals("")){

                            String url = "http://www.niaolema.com/mobile/index.php?act=member_favorites_store&op=favorites_add";
                            String params ="key=" + key + "&store_id=" + store_id;
                            String result = HttpUtils.doPost(url, params);
                            OSList = OneSyombJson.getOneSyomb(result);
                            //if(OSList.getError().equals("")){
                            handler.sendEmptyMessage(3);
                            //}

                        } else {

                            String url = "http://www.niaolema.com/mobile/index.php?act=member_favorites_store&op=favorites_add";
                            String params ="key=" + key + "&store_id=" + store_id;
                            String result = HttpUtils.doPost(url, params);
                            if (!result.equals("") && !result.equals("null")) {
                                SList = SyombJson.getSyomb(result);
                                if (SList.getDatas() == 1) {
                                    //获取数据成功
                                    handler.sendEmptyMessage(2);
                                } else {
                                    handler.sendEmptyMessage(0);
                                }

                            }
                        }


                    }
                }).start();


            }
        });
        //拨号监听事件
        phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "020-87781618"));
                if (ActivityCompat.checkSelfPermission(BrokerDealerActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                startActivity(intent);
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Intent intent = new Intent();
                //setResult(112,intent);
                finish();
            }
        });
        all_goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(BrokerDealerActivity.this, FlagshipStoreActivity.class);
                startActivity(intent);

            }
        });
        et_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(BrokerDealerActivity.this, FlagshipStoreActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.translatein,R.anim.translateout);

            }
        });

        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(BrokerDealerActivity.this, FlagshipStoreActivity.class);
                startActivity(intent);

            }
        });

    }



    private void initView() {

        phone = (RelativeLayout) findViewById(R.id.rl_phone);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        et_search = (EditText) findViewById(R.id.et_search);

        all_goods = (LinearLayout) findViewById(R.id.all_goods);
        //进度加载
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        //商店描述
        iv_store_credit = (ImageView) findViewById(R.id.store_credit);
        //关注
        tv_attention = (TextView) findViewById(R.id.tv_attention);
        iv_attention = (RadioButton) findViewById(R.id.iv_attention);
        rl_attention = (RelativeLayout) findViewById(R.id.rl_attention);
        qq = (RelativeLayout) findViewById(R.id.QQ);

        //分享
        share = (RelativeLayout) findViewById(R.id.share);
        share.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share:
                shareDialog = new ShareDialog(this);
                shareDialog.setCancelButtonOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        shareDialog.dismiss();

                    }
                });
                shareDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        HashMap<String, Object> item = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);


                        if (item.get("ItemText").equals("QQ")) {
                            ShareParams sp = new ShareParams();
                            sp.setTitle("尿了母婴商城");
                            sp.setTitleUrl("http://www.niaolema.com"); // 标题的超链接
                            sp.setText("我在尿了母婴商城旗舰店找到超级优惠的店铺，各种新品正在热卖，快来抢吧！" +
                                    "下载APP更有好礼相送，去看看吧！");
                            sp.setImageUrl("http://www.niaolema.com/data/upload/shop/store/goods/1/1_05189008095831994_360.jpg");//分享网络图片

                            Platform qq = ShareSDK.getPlatform(QQ.NAME);
                            qq.setPlatformActionListener(BrokerDealerActivity.this); // 设置分享事件回调
                            // 执行分享
                            qq.share(sp);
                        }else if(item.get("ItemText").equals("SinaWeibo")){
                            SinaWeibo.ShareParams sp = new SinaWeibo.ShareParams();
                            sp.setTitle("分享的标题");
                            sp.setTitleUrl("http://sharesdk.cn"); // 标题的超链接
                            sp.setText("分享的文本");
                            sp.setImageUrl("http://www.niaolema.com/data/upload/shop/store/05181180502367018.png");//分享网络图片

                            Platform wc = ShareSDK.getPlatform(SinaWeibo.NAME);
                            wc.setPlatformActionListener(BrokerDealerActivity.this); // 设置分享事件回调
                            // 执行分享
                            wc.share(sp);

                        }

                    }
                });

                break;

            default:
                break;
        }
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

        if(platform.getName().equals(QQ.NAME)) {
            handler.sendEmptyMessage(1);

        }else {
            handler.sendEmptyMessage(2);
        }


    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        throwable.printStackTrace();
        Message msg = new Message();
        msg.what = 5;
        msg.obj = throwable.getMessage();
        handler.sendMessage(msg);
    }

    @Override
    public void onCancel(Platform platform, int i) {

        handler.sendEmptyMessage(4);
    }

    //请求网络数据 //开启线程
    private void getDataFromWeb() {

        progressBar.setVisibility(View.VISIBLE);


        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用HttpUtils类，来请求网络获取Json数据
                String result = HttpUtils.doGet(Constants.BROKERDEALER_LIST_URL);
                //是否获取到Json数据
                if (!result.equals("") && !result.equals("null")) {

                    //将获取到的json数据解析，通过封装的工具类
                    list = BrokerdealerJson.getBrokerdealer(result);

                    //判断解析出的集合的长度，有数据就显示，无数据就不显示
                    if (list.size() > 0) {

                        //获取数据成功
                        handler.sendEmptyMessage(1);
                    } else {
                        //失败
                        handler.sendEmptyMessage(0);
                    }

                } else {
                    //获取Json数据失败
                    handler.sendEmptyMessage(0);

                }


            }
        }).start();


    }

    //商店描述 弹出对话框
    private void showDialogStore() {
        //绑定布局控件
        View view = LayoutInflater.from(this).inflate(R.layout.store_credit_dialog, null);
        TextView textView = (TextView) view.findViewById(R.id.tv_store_credit);
        new AlertDialog.Builder(this).setView(view).show();


    }
    private void showDialogQQ() {
        View view = LayoutInflater.from(this).inflate(R.layout.qq_dialog,null);
        TextView text = (TextView) view.findViewById(R.id.tv_store_credit);
        new AlertDialog.Builder(this).setView(view).show();


    }
    public void showDialogAgain(final Context context, String msg, boolean goHome) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context).setMessage(msg).setCancelable(false);

        //设置图标
        builder.setIcon(R.mipmap.ic_launcher);
        //设置标题
        builder.setTitle("提示");
        builder.setPositiveButton("请点击这里重新加载", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                getDataFromWeb();
            }
        });

        //创建并显示
        builder.create().show();
    }

    //设置图片距离
    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = space;
            }
        }
    }
}
